using System;
using System.IO;
using System.Net;
using System.Reflection;
using SQLRunnerLib.Services;
using SQLServices.Log;


namespace SQLRunnerLib.VersionCheck
{

	//public delegate void CheckVersionHandler(SQLVersion webVersion, bool isNewVersion);

	public class URLChecker
	{
		
		private SQLRunnerVersion _webVersion;

		public URLChecker(){}

		private Stream GetFile(string url)
		{
			WebClient client = new WebClient();
			return client.OpenRead(url);
		}

		private void ParseVersionFile(Stream versionFile)
		{
			_webVersion = SQLRunnerVersion.Deserialize(new StreamReader(versionFile));			
		}

		private bool IsNewVersion(string url, System.Version version)
		{
			if ( _webVersion != null )
			{
				return ( _webVersion.Version.CompareTo(version) > 0 );
			}
			return false;
		}

		public SQLRunnerVersion CheckVersion(string url, System.Version version)
		{
			try
			{
				ParseVersionFile(GetFile(url));	
			}
			catch (Exception ex)
			{
				ServiceContainer.Logger.LogMessage(
					String.Format("URLChecker - Error: {0}", ex.Message), 
					MsgLevel.Error);
			}
			return _webVersion;
		}

		public System.Version GetVersionFromAssembly(Assembly ass)
		{			
			return Assembly.GetExecutingAssembly().GetName().Version;
		}
	}
}
